# from PIL import ImageGrab

import numpy as np
import cv2
import time
from PIL import Image


def get2img(img_data):
    img_data = cv2.cvtColor(img_data, cv2.COLOR_RGB2GRAY)
    # _, img_data = cv2.threshold(img_data, 99, 0, cv2.THRESH_TOZERO_INV)
    _, img_data = cv2.threshold(img_data, 40, 255, cv2.THRESH_BINARY)
    return img_data


# screenshot_pil = ImageGrab.grab()
# image_data = np.array(screenshot_pil)
# image_data = cv2.cvtColor(image_data, cv2.COLOR_RGB2BGR)
sample = cv2.imread('yanwei.png')
template = cv2.imread('yw.png')
# 模板二值图
template = get2img(template)
# 获取模板图像的尺寸
# w = template.shape[1]
# h = template.shape[0]
# start_time = time.time()
# res = cv2.matchTemplate(get2img(sample), template, cv2.TM_CCORR_NORMED)
# end_time = time.time()  # 记录程序结束时间
# elapsed_time = end_time - start_time
#
# threshold = 0.75  # 设定阈值
# loc = np.where(res >= threshold)
# # 标记匹配位置
# for pt in zip(*loc[::-1]):
#     x = pt[0]
#     y = pt[1]
#     # 提取指定区域的色相
#     # roi = sample[y:sh, x:sw]
#     # mean_hue = np.mean(roi[:, :, 0])  # 计算指定区域的平均色相
#     # print(mean_hue)
#     # pyautogui.moveTo(fx, fy)
#     cv2.rectangle(sample, (x, y), (x+w, y+h), (0, 255, 255), 1)
# sample = cv2.resize(sample, (960, 512))
window_name = 'test'
cv2.namedWindow(window_name)

# 设置窗口的位置
x_pos = 100  # 窗口左上角的 x 坐标
y_pos = 100  # 窗口左上角的 y 坐标
cv2.moveWindow(window_name, x_pos, y_pos)
# 显示调整后的图像
x1, y1 = 1500, 600  # 左上角坐标
x2, y2 = 1920, 1080  # 右下角坐标
sample = sample[y1:y2, x1:x2]
# cv2.imshow(window_name, get2img(sample))
# cv2.imshow(window_name, sample)
cv2.imshow(window_name, template)
cv2.waitKey(0)
cv2.destroyAllWindows()
